//! json相关工具
//!
//! ## 示例
//!
//! ```
//! use serde_json::json;
//! use wang_utils_json::write_json_to_file;
//!
//! #[test]
//! fn test_write_json_to_file() -> anyhow::Result<()> {
//!   let json = json!({
//!       "user":"123312",
//!       "pwd":"user-pwd"
//!   });
//!   write_json_to_file("test.json", &json)?;
//!   Ok(())
//! }
//! ```
#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate self as wang_utils_json;

use serde::Serialize;
use std::fs;
use std::path::Path;

/// 转json后写入文件
pub fn write_json_to_file<P: AsRef<Path>, T>(path: P, value: &T) -> anyhow::Result<()>
where
    T: ?Sized + Serialize,
{
    let result = serde_json::to_string(value)?;
    fs::write(path, result)?;
    Ok(())
}
/// 转json后写入文件，与write_json_to_file的区别是对json进行了格式化
pub fn write_pretty_json_to_file<P: AsRef<Path>, T>(path: P, value: &T) -> anyhow::Result<()>
where
    T: ?Sized + Serialize,
{
    let result = serde_json::to_string_pretty(value)?;
    fs::write(path, result)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_write_json_to_file() -> anyhow::Result<()> {
        let json = json!({
            "user":"123312",
            "pwd":"user-pwd"
        });
        println!("{:#?}", json);
        write_pretty_json_to_file("test.json", &json)?;
        fs::remove_file("test.json")?;
        Ok(())
    }
}
